from django.shortcuts import render
from rest_framework_jwt.views import JSONWebTokenAPIView
from .serializers import CustomJSONWebTokenSerializer
from rest_framework.views import APIView
from . import models
import re
from rest_framework.response import Response
from rest_framework import status
from .utils import get_user_obj_by_account
import random
# from .serializers import RegisterModelSerializer
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
from .serializers import RegisterSerializer
import logging
logger = logging.getLogger('django')

class LoginView(JSONWebTokenAPIView):

    serializer_class =CustomJSONWebTokenSerializer

class CheckPhoneView(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        #格式校验
        if not re.match('1\d{10}',phone):
            return Response({'error':'手机号格式有误！'},status=status.HTTP_400_BAD_REQUEST)
        #校验手机号唯一性
        ret = get_user_obj_by_account(phone)
        if ret:
            return Response({'error':'手机号已被注册！'},status=status.HTTP_400_BAD_REQUEST)
        return Response({'msg':'OK'})

class RegisterView(CreateAPIView):

    queryset = models.User.objects.all()
    serializer_class = RegisterSerializer


from lyapi.libs.yuntongxun.send_sms import send_message
from lyapi.settings import contains


class SMScodeView(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        #生成验证码
        code = '%04d' % random.randint(0,9999)
        #手机号的各种校验
        user = get_user_obj_by_account(phone)
        if user:
            return Response({'error':'手机号已经被注册过了！！！'},status = status.HTTP_400_BAD_REQUEST)
        # #保存验证码   方法一
        # conn = get_redis_connection('sms_code')
        # # 在保存数据之前,先到redis中查询一下,是否在60秒内已经发送过短信了,如果能查到之,表示60秒内已经发送过了
        # redis_inter_code = conn.get('sms_inter_%s' % phone)
        # if redis_inter_code:
        #     return Response({'error':'你点太快了,老弟,再等会儿'},status = status.HTTP_400_BAD_REQUEST)
        # conn.setex('sms_%s' % phone,contains.SMS_EXIPRE_TIME*60,code)
        # conn.setex('sms_inter_%s' % phone,contains.SMS_INTERVAL_TIME,code)

        # 保存验证码  方法二
        conn = get_redis_connection('sms_code')
        pipe = conn.pipeline()  # 创建管道
        pipe.multi()  # 开启批量操作  (事务)
        # 在保存数据之前,先到redis中查询一下,是否在60秒内已经发送过短信了,如果能查到之,表示60秒内已经发送过了
        redis_inter_code = conn.get('sms_inter_%s' % phone)
        if redis_inter_code:
            return Response({'error': '你点太快了,老弟,再等会儿'}, status=status.HTTP_400_BAD_REQUEST)
        pipe.setex('sms_%s' % phone, contains.SMS_EXIPRE_TIME * 60, code)
        pipe.setex('sms_inter_%s' % phone, contains.SMS_INTERVAL_TIME, code)
        pipe.execute() # 批量执行

        #发送验证码
        # ret = send_message(phone,code)
        from mycelery.sms.tasks import send_sms
        send_sms.delay(phone,code)
        # ret = True
        # if not ret:
        # # if True:
        #     return Response({'error':'短信发送失败'},status = status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     return Response({'msg':'短信发送成功，请查收'})
        return Response({'msg': '短信发送成功，请查收'})